<script setup lang="ts">
import TableTemplate from './components/TableTemplate.vue';
import BatchAddTemplate from './components/batchAddTemplate.vue';
import DialogTemplate from './components/dialogTemplate.vue';
import {ElMessage, ElMessageBox} from "element-plus";
import {
  addCertificationInformation,
  deleteCertificationInformation,
  editCertificationInformation, exportCertificationInformation,
  getCertificationInformationList,
} from "../account/accountApi.js";

const loading = ref(false)
let dataSet = reactive({
  queryBox: [
    {
      model: 'username',
      type: 'input',
      placeholder: '请输入用户名称'
    },

    {
      model: 'userType',
      type: 'select',
      placeholder: '请选择用户类型',
      options: [
        {label: '学生', value: 0},
        {label: '教师', value: 1},
        {label: '管理员', value: 2},
      ],
    },
    {
      model: 'mobile',
      type: 'input',
      placeholder: '请输入手机号'
    },
    {
      model: 'email',
      type: 'input',
      placeholder: '请输入邮箱'
    }
  ],
  tableList: [
    {prop: 'username', label: '用户名', width: '120'},
    {prop: 'mobile', label: '手机号', width: '150'},
    {prop: 'workNumber', label: '认证号', width: '150'},
    {prop: 'email', label: '邮箱', width: '180'},
    {prop: 'createDate', label: '创建时间', width: '180'},
    {prop: 'updateDate', label: '更新时间', width: '180'},
  ],
  tnQueryTop: [
    {name: '新增', click: 'userAdd', type: 'primary'},
    {name: '批量新增', click: 'userBatchAdd', type: 'success'},
    {name: '批量删除', click: 'userBatchDelete', type: 'danger'},
    {name: '导出', click: 'userExport', type: 'primary'},
    {name: '全部导出', click: 'userAllExport', type: 'info'}
  ],
  operationBtns: [
    {name: '编辑', click: 'userEdit', type: 'primary'},
    {name: '删除', click: 'deleteId', type: 'danger'},
    {name: '详情', click: 'userDetail', type: 'info'},
  ],
  tableData: {
    total: 0,
    rows: []
  }
})

let batchAddVisible = reactive({
  fileName: '用户认证数据批量添加Excel模板.xlsx',
  dialogFormVisibles: false,
})
// 弹窗 数据
const registerDialogRef = ref(null)
const registerTableRef = ref(null)
const title = ref('认证数据新增')
const dialogTemplateRef = ref(null)
const dialogTemplateVisible = ref(false)
const formItems = ref([{
  list: [
    {
      label: '用户名',
      prop: 'username',
      type: 'input',
      rules: [
        {required: true, message: '请输入用户名', trigger: 'blur'},
        {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
      ],
      placeholder: '请输入用户名'
    },
    {
      label: '手机号',
      prop: 'mobile',
      type: 'input',
      rules: [
        {required: true, message: '请输入手机号', trigger: 'blur'},
        {min: 11, max: 11, message: '长度为11位', trigger: 'blur'}
      ],
      placeholder: '请输入手机号'
    },
    {
      label: '认证号',
      prop: 'workNumber',
      type: 'input',
      rules: [
        {required: true, message: '请输入认证号', trigger: 'blur'},
        {min: 11, max: 18, message: '长度为11-18位', trigger: 'blur'}
      ],
      placeholder: '请输入认证号'
    },
    {
      label: '邮箱',
      prop: 'email',
      type: 'input',
      rules: [
        {required: true, message: '请输入邮箱', trigger: 'blur'},
        {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
      ],
      placeholder: '请输入邮箱'
    },
    {
      label: '用户类型',
      prop: 'userType',
      type: 'select',
      options: [
        {label: "学生", value: 0}
        , {label: "教师", value: 1}
        , {label: "管理员", value: 2}
      ],
      rules: [
        {required: true, message: '请选择用户类型', trigger: 'blur'}
      ],
      placeholder: '请选择用户类型'
    },
  ]
}])
// 表单数据
const initialData = ref({})
//查看为true，其他为false
const isViewMode = ref(false)
// 操作名称 新增，编辑 详情
const operationName = ref('')
const handleDialogSubmit = async (data) => {
  if (operationName.value === '新增') {
    await addCertificationInformation([data]).then(res => {
      if (res.code === 0) {
        ElMessage.success('新增成功')
        dialogTemplateVisible.value = false;
        dialogTemplateRef.value.dialogTemplateVisible = false;
        resetSubmit({});
        return;
      }
      ElMessage.error(res.message || '新增失败')
    });
  } else {
    await editCertificationInformation(data).then(res => {
      if (res.code === 0) {
        ElMessage.success('编辑成功')
        dialogTemplateVisible.value = false;
        dialogTemplateRef.value.dialogTemplateVisible = false;
        selectSubmit({});
        return;
      }
      ElMessage.error(res.message || '编辑失败')
    });
  }
}
// 重置
const resetSubmit = (data) => {
  selectSubmit(data);
}
// 查询
const selectSubmit = async (data) => {
  loading.value = true;
  await getCertificationInformationList(data).then(res => {
    dataSet.tableData.rows = res.data.records
    dataSet.tableData.total = res.data.total
  }).finally(() => {
    loading.value = false;
  });
}
selectSubmit({})
//新增
const userAdd = () => {
  operationName.value = '新增'
  isViewMode.value = false
  title.value = '认证数据新增'
  initialData.value = {}
  dialogTemplateVisible.value = true;
  dialogTemplateRef.value.dialogTemplateVisible = true;
}
// 批量新增
const userBatchAdd = () => {
  batchAddVisible.dialogFormVisibles = true
}
const handleIndex = ref([])
const handleChange = (data) => {
  handleIndex.value = data
}
// 批量删除
const userBatchDelete = async () => {
  if (handleIndex.value.length === 0) {
    ElMessage.error('请至少选择一条数据！')
    return;
  }
  ElMessageBox.confirm(
      '确定要删除这些项目吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    let ids = handleIndex.value.map(item => item.id)
    await deleteCertificationInformation(ids).then(res => {
      if (res.code === 0) {
        ElMessage.success('删除成功')
        registerTableRef.value?.clearSelection();
        resetSubmit({});
        return;
      }
      ElMessage.error(res.message || '删除失败')
      registerTableRef.value?.clearSelection();
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    })
  })
}
// 导出
const userExport = () => {
  if (handleIndex.value.length < 1) {
    ElMessage.error("请选择要导出的数据！")
    return
  }
  exportCertificationInformation(handleIndex.value);
  handleIndex.value = [];
  registerTableRef.value?.clearSelection();
}
// 全部导出
const userAllExport =async () => {
  await getCertificationInformationList({pageNum: 1, pageSize: 999999999}).then(res => {
    exportCertificationInformation(res.data.records);
  });
}

// 编辑
const userEdit = (data) => {
  operationName.value = '编辑'
  isViewMode.value = false
  title.value = '认证数据编辑'
  initialData.value = {...data}
  dialogTemplateVisible.value = true;
  dialogTemplateRef.value.dialogTemplateVisible = true;
}
// 删除
const deleteId = async (data) => {
  await deleteCertificationInformation([data.id]).then(res => {
    if (res.code === 0) {
      ElMessage.success('删除成功')
      registerTableRef.value?.clearSelection();
      selectSubmit({});
      return;
    }
    ElMessage.error(res.message || '删除失败')
  });
}
// 详情
const userDetail = (data) => {
  operationName.value = '详情'
  isViewMode.value = true
  title.value = '认证数据详情'
  initialData.value = {...data}
  dialogTemplateVisible.value = true;
  dialogTemplateRef.value.dialogTemplateVisible = true;
}
// 批量新增提交
const batchAddSubmit = async (fileList, username) => {
  // 必须包含的字段
  const requiredFields = ['用户姓名', '认证号','手机号','邮箱','用户类型'];

  // 检查 fileList 的字段
  const isValidFile = fileList.every(item =>
      requiredFields.every(field => Object.prototype.hasOwnProperty.call(item, field))
  );

  if (!isValidFile) {
    ElMessage.error("文件格式错误，请上传正确的模板文件！");
    return;
  }
  // 构造数据
  const data = fileList.map(item => ({
    username: item.用户姓名,
    mobile: item.手机号,
    workNumber: item.认证号,
    email: item.邮箱,
    userType: item.用户类型 === "学生" ? 0 : item.用户类型==="教师"?1:2,
  }));

  if (data.length < 1) {
    ElMessage.error("文件内容为空，请检查模板文件！");
    return;
  }
  //批量新增
  let response = await addCertificationInformation(data);
  if (response.code === 0) {
    ElMessage.success("批量新增成功");
    batchAddVisible.dialogFormVisibles = false;
    selectSubmit({});
    return;
  }
  ElMessage.error(response.message || "批量新增失败，请检查表单");
};


</script>

<template>
  <div class="container">
    <TableTemplate
        ref="registerTableRef"
        :data-set="dataSet"
        @userAdd="userAdd"
        @userEdit="userEdit"
        :getStatusColor="getStatusColor"
        @deleteId="deleteId"
        @userDetail="userDetail"
        @userBatchDelete="userBatchDelete"
        @userBatchAdd="userBatchAdd"
        @reset-submit="resetSubmit"
        @userExport="userExport"
        @handleChange="handleChange"
        @userAllExport="userAllExport"
        @select-submit="selectSubmit"
        :loading="loading"
    />
    <BatchAddTemplate
        ref="registerDialogRef"
        v-model="batchAddVisible.dialogFormVisibles"
        @submit-adds="batchAddSubmit"
        @userBatchAdd="userBatchAdd"
        :batch-add-visible="batchAddVisible"
    />
    <DialogTemplate
        v-model="dialogTemplateVisible"
        ref="dialogTemplateRef"
        :title="title"
        :width="'500px'"
        :initial-data="initialData"
        :form-items="formItems"
        :is-view="isViewMode"
        @handleDialogSubmit="handleDialogSubmit"
        :operation-name="operationName"
    />
  </div>

</template>

<style scoped lang="scss">

</style>
